package cn.wolfcode.rbac.web.interceptor;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.util.RequiredPermission;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行2。。。拦截权限");
        //是不是管理员
        Employee e = UserContext.getCurrentUser();
        if(e.isAdmin()){
            return true;
        }
        /*System.out.println(handler);
        System.out.println(handler.getClass());*/
        //处理注解表达式
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            //通过反射获取注解类中的方法或属性等信息
            RequiredPermission annotation = (RequiredPermission)handlerMethod.getMethodAnnotation(RequiredPermission.class);
            if(annotation == null){
                return true;
            }
            //获取类名，simplename是获取名字不带包名，name是带包名
            String simpName = handlerMethod.getBean().getClass().getSimpleName().replace("Controller","");
            System.out.println("simpMane===  "+simpName);
            //大写字母转小写，得到方法名
            String expression = StringUtils.uncapitalize(simpName)+":"+handlerMethod.getMethod().getName();
            //获取到SESSION中的EXPRESSION_IN_SESSION值
            List<String> permission = UserContext.getExpression();

            if(permission.contains(expression)){
                return true;
            }
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response);
        }
        return false;
    }
}